package com.re6g3y.game.mulitThread;

import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Disposable;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class WorldStepThread implements Disposable{

    private World world;
    private Thread thread;
    private BlockingQueue<Runnable> queue=new LinkedBlockingQueue<Runnable>();
    private boolean isdispose=false;
    public WorldStepThread(World world){
        this.world=world;
        thread=new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    if(isdispose)break;
                    try {
                        queue.take().run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.setName("WorldStepThread");
        thread.start();
    }

    public void step(final float time,final int v,final int p){
        try {
            queue.put(new Runnable() {
                @Override
                public void run() {
                    world.step(time,v,p);
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void dispose(){
        isdispose=true;
        try {
            queue.put(new Runnable() {
                @Override
                public void run() {

                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void waitForFinish(){
        final WorldStepThread d=this;
        try {
            synchronized (d) {
                queue.put(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (d) {
                            d.notify();
                        }
                    }
                });
                d.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
